package com.jerei.crm.service.impl;

import com.jerei.crm.entity.User;
import com.jerei.crm.mapper.UserMapper;
import com.jerei.crm.service.IUserService;
import com.jerei.crm.service.ex.InsertException;
import com.jerei.crm.service.ex.PasswordNotMatchException;
import com.jerei.crm.service.ex.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void addUser(String username,String password) {
        User u=userMapper.selectByUsername(username);
        if(u!=null){
            throw new InsertException("注册失败！用户名以存在");
        }
        User user=new User();
        String salt= UUID.randomUUID().toString();
        user.setSalt(salt);
        String md5Password=getMd5Password(salt,password);
        user.setPassword(md5Password);
        user.setUsername(username);
        Integer rows=userMapper.register(user);
        if(rows!=1){
            throw new InsertException("注册失败！请重新尝试");
        }
    }

    @Override
    public User login(String username, String password) {

        //输出日志
        System.out.println("UserServiceImpl.login()");
        System.out.println("username="+username);
        System.out.println("password="+password);
        //根据用户名调用findByUsername查询
        User user=userMapper.selectByUsername(username);
        //判断查询结果是否为null
        if(user==null){
            //是：抛出UserNotFindException
            throw new UserNotFoundException("登陆失败！用户名不存在");
        }

        //从查询结果中取出盐值
        String salt=user.getSalt();
        //基于参数password与取出的盐值执行加密得到密文
        String pwd=getMd5Password(salt,password);
        //判断以上密文与查询结果中的密文是否不一致
        if(!pwd.equals(user.getPassword())){
            //不一致，则抛出passwordNotMatvhException
            throw new PasswordNotMatchException("登陆失败！密码错误");
        }
        //创建新的User对象
        User u=new User();
        //将查询结果中的uid、username封装到新创建的User中
        u.setUsername(username);
        u.setUid(user.getUid());

        //返回新创建的User对象
        return u;
    }


    /**
     * 执行密码加密，获取加密后的密码
     * @param salt 盐值
     * @param password 原始密码
     * @return 加密后的密码
     */
    private String getMd5Password(String salt,String password){
        /*
        加密规则：
            1.使用“盐+密码+盐”作为原文
            2.执行三重加密
         */
        System.out.println("原始密码"+password);
        System.out.println("盐值"+salt);
        for(int i=0;i<3;i++){
            password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes());
        }
        System.out.println("加密后"+password);
        return password;
    }

}
